package com.zzyl.nursing.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.job.vo.IotMsgNotifyData;
import com.zzyl.nursing.job.vo.IotMsgService;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 设备数据Service业务层处理
 * 
 * @author ZHD
 * @date 2025-08-23
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceMapper  deviceMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return deviceDataMapper.deleteById(id);
    }

    /**
     * 获取IOT平台上的数据
      * @param iotMsgNotifyData 设备数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        if(ObjectUtils.isNull(iotMsgNotifyData)){
            throw new BaseException("设备数据获取异常");
        }
        //1.通过设备ID查询设备信息
        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
        Device device = deviceMapper.selectOne(
                new LambdaQueryWrapper<Device>()
                        .eq(Device::getIotId, deviceId));
        //2.设备是否存在
        if(ObjectUtils.isNull(device)){
            throw new BaseException("设备不存在");
        }
        //3.设备存在,解析从IOT平台获取的设备数据
        List<IotMsgService> services = iotMsgNotifyData.getBody().getServices();
        // 4.封装成List<DeviceData>
        List<DeviceData> deviceDataList = new ArrayList<>();
        services.forEach(item -> {
            LocalDateTime alarmTime = LocalDateTimeUtil.parse(item.getEventTime(), Constants.LOCAL_DATE_TIME_FORMATTER)
                    .atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.systemDefault())
                    .toLocalDateTime();
            item.getProperties().forEach((key, value) -> {
                DeviceData deviceData = new DeviceData();
                deviceData.setDeviceName(device.getDeviceName());
                deviceData.setIotId(deviceId);
                deviceData.setProductKey(device.getProductKey());
                deviceData.setProductName(device.getProductName());
                deviceData.setFunctionId(key);
                deviceData.setAccessLocation(device.getRemark());
                deviceData.setLocationType(device.getLocationType());
                deviceData.setPhysicalLocationType(device.getPhysicalLocationType());
                deviceData.setDeviceDescription(device.getDeviceDescription());
                deviceData.setDataValue(value);
                deviceData.setAlarmTime(alarmTime);
                deviceData.setRemark(device.getRemark());
                deviceDataList.add(deviceData);
            });
        });
        this.saveBatch(deviceDataList);
        //5.保存设备数据
        redisTemplate.opsForHash().put(Constants.IOT_DEVICE_LAST_DATA, deviceId, deviceDataList);
    }

    @Override
    public TableDataInfo<DeviceData> pageQuery(DeviceDataPageReqDto deviceDataPageReqDto) {
        String deviceName = deviceDataPageReqDto.getDeviceName();
        String functionId = deviceDataPageReqDto.getFunctionId();
        LocalDateTime startTime = deviceDataPageReqDto.getStartTime();
        LocalDateTime endTime = deviceDataPageReqDto.getEndTime();
        Page<DeviceData> page = Page.of(deviceDataPageReqDto.getPageNum(), deviceDataPageReqDto.getPageSize());
        this.lambdaQuery()
                .eq(StringUtils.isNotBlank(deviceName), DeviceData::getDeviceName, deviceName)
                .eq(StringUtils.isNotBlank(functionId), DeviceData::getFunctionId, functionId)
                .between(Objects.nonNull(startTime) && Objects.nonNull(endTime), DeviceData::getAlarmTime, startTime, endTime)
                .page(page);
        TableDataInfo<DeviceData> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询物模型数据成功");
        return tableDataInfo;
    }
}
